<template>
    <div class="storefile">
        <div style="border-left: 1px solid #e9e7e7;border-right: 1px solid #e9e7e7;min-height:300px;">
            <div class="fileNav">
                <div>
                    <img src="../../assets/img/返回.png" @click="returnLastFolder" v-if="parentlist.length > 1"
                        style="width:25px;height:25px;cursor: pointer;margin:0 10px;" />
                </div>
                <div class="upload">
                    <el-button size="small">上传</el-button>
                    <div class="uploadHover">
                        <li @click="createFolder">新建文件夹</li>
                        <li @click="createArticle">新建文章</li>
                        <li @click="uploadFile">
                            上传附件
                            <input type="file" @change="changeFile" id="fileToUpload" />
                        </li>
                    </div>
                </div>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;color:#5c5c5c;margin:10px 15px;">
                <div>文件名</div>
                <div>上传者</div>
            </div>
            <li class="files" v-if="showInputFileName">
                <div class="fileitem"><img src="../../assets/img/24gf-folderOpen.png" class="folder" />
                    <el-input class="inputFile" autofocus size="medium" maxlength="20" v-model="inputFileName"
                        @blur="uploadFolder" />
                </div>
                <div class="creator">
                    {{ user.username }}
                </div>
            </li>
            <el-empty description="暂无文档" style="flex:1" v-if="currentFiles.length < 1 && !showInputFileName"></el-empty>
            <div class="list">
                <li v-for="f in currentFiles" :key="f.id" class="files" :id="'li' + f.id" @click="clickFileItem(f)">
                    <div class="fileitem">
                        <img v-if="f.type === 1" src="../../assets/img/文件.png" class="folder" />
                        <img v-if="f.type === 2" src="../../assets/img/24gf-folderOpen.png" class="folder" />
                        <img v-if="f.type === 3" src="../../assets/img/_attachment.png" class="folder" />
                        <div style="font-size:14px;margin-left:10px">
                            <span id="filetitle">{{ f.filetitle }}</span>
                            <div v-on:click.stop>
                                <el-input autofocus size="medium" maxlength="20" class="inputReName" id="inputReName"
                                    @blur="changeFileName(f.id)" v-model="FileReName"></el-input>
                            </div>
                        </div>
                    </div>
                    <div class="creator" v-if="hasjoin">
                        <el-button type="text" v-on:click.stop="moveFile(f)" style="font-size:12px;margin-right:10px;color: #2680f6;">迁移</el-button>
                        <a v-if="f.type === 3" v-on:click.stop="downloadFile(f.typeid)" class="downloadBt">下载</a>
                        <el-button type="text" v-if="f.founderid === user.id && f.type !== 3"
                            v-on:click.stop="editFile(f)"><i class="el-icon-edit"></i></el-button>
                        <el-button type="text" v-if="f.founderid === user.id" v-on:click.stop="deleteFile(f)"><i
                                class="el-icon-delete"></i></el-button>
                        {{ f.username }}
                    </div>
                </li>
            </div>
            <el-dialog title="迁移文件" :visible.sync="showMoveDialog" width="25%">
                <div class="block">
                    <span>迁移至：</span><el-cascader v-model="MoveToFileItemid" placeholder="搜索" :options="filesTree"
                        filterable :props="{ value: 'id', label: 'filetitle',checkStrictly: true }" size="small" ></el-cascader>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="showMoveDialog = false" size="medium">取 消</el-button>
                        <el-button type="primary" @click="moveFileConfirm()" size="medium">确 定</el-button>
                    </div>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>

import { getStoreFile, uploadFile, createFiles, getAnnex, deleteFile, updateFileName, moveFile } from '../../api/api'
import download from 'downloadjs'; // 引用插件
export default {
    name: 'storefile',
    props:['hasjoin'],
    data() {
        return {
            user: JSON.parse(window.sessionStorage.getItem('user')),
            files: [],
            currentFiles: [],
            filesTree: [{ id: 0, filetitle: '全部文档', children: [] }],
            moveFileItem: {},
            MoveToFileItemid: [],
            showMoveDialog: false,
            parentlist: [0],
            inputFileName: '',
            showInputFileName: false,
            FileReName: ''
        }
    },
    created() {
        getStoreFile(this.$route.params.id).then(res => {
            if (res.data.code == 200) {
                this.files = res.data.data;
                this.getCurrentFile(0);
            }
        })
    },
    methods: {
        formatToTree(ary, pid, pidName = 'parentid') {
            return ary
                .filter((item) => item[pidName] === pid)
                .map((item) => {
                    // 通过父节点ID查询所有子节点
                    let tmp = this.formatToTree(ary, item.id);
                    if (tmp.length > 0) item.children = tmp;
                    return item;
                });
        },
        moveFile(f) {
            this.moveFileItem = f;
            this.filesTree[0].children = this.formatToTree(this.files.filter(item => item.type == 2 && item.id !== f.id), 0);
            this.showMoveDialog = true;
        },
        moveFileConfirm() {
            let tmp = {
                id: this.moveFileItem.id,
                moveTo: this.MoveToFileItemid[this.MoveToFileItemid.length - 1]
            }
            moveFile(tmp).then(res => {
                if (res.data.code == 200) {
                    this.$notify({
                        title: '成功',
                        message: '迁移成功！',
                        type: 'success'
                    });
                    getStoreFile(this.$route.params.id).then(res => {
                        if (res.data.code == 200) {
                            this.files = res.data.data;
                            this.getCurrentFile(0);
                            this.showMoveDialog = false;
                            this.filesTree = [{ id: 0, filetitle: '全部文档', children: [] }]
                        }
                    })
                    this.parentlist = [0];
                    this.moveFileItem = {};
                    this.MoveToFileItemid = [];
                } else {
                    this.$notify.error({
                        title: 'error',
                        message: '迁移失败，请稍后重试'
                    });
                }
            });
        },
        downloadFile(id) {
            getAnnex(id).then(res => {
                download(res.data.url);
            })
        },
        getCurrentFile(parentId) {
            this.currentFiles = this.files.filter(items => items.parentid === parentId);
        },
        clickFileItem(item) {
            if (item.type === 1) {
                this.$router.push(`/article/${item.typeid}`)
            } else if (item.type === 2) {
                this.getCurrentFile(item.id);
                this.parentlist.push(item.id);
            }
        },
        returnLastFolder() {
            this.parentlist.pop();
            this.getCurrentFile(this.parentlist[this.parentlist.length - 1])
        },
        createArticle() {
            this.$router.push('/write/' + this.$route.params.id + '/' + this.parentlist[this.parentlist.length - 1]);
        },
        createFolder() {
            this.showInputFileName = true;
        },
        uploadFolder() {
            if (this.inputFileName.length < 1) {
                this.$message('已取消');
                this.showInputFileName = false;
                return;
            }
            let tmp = {
                title: this.inputFileName,
                type: 2,
                parentid: this.parentlist[this.parentlist.length - 1],
                storeid: this.$route.params.id,
            }
            createFiles(tmp).then(res => {
                if (res.data.code === 200) {
                    this.$message.success('新建文件夹成功');
                    this.inputFileName = '';
                    getStoreFile(this.$route.params.id).then(res => {
                        if (res.data.code == 200) {
                            this.showInputFileName = false;
                            this.files = res.data.data;
                            this.getCurrentFile(this.parentlist[this.parentlist.length - 1]);
                        }
                    })
                } else {
                    this.$message.error(res.data.message);
                }
            })
        },
        // 二进制流转换为base64 格式。
        getBase64(data) {
            return new Promise((resolve, reject) => {
                const blob = new Blob([data], {
                    type: data.type
                }); //类型一定要写！！！
                const reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = () => resolve(reader.result);
                reader.onerror = (error) => reject(error);
            });
        },
        uploadFile() {
            document.getElementById('fileToUpload').click()
        },
        changeFile(e) {
            //   获取文件
            this.file = e.target.files[0];
            this.getBase64(this.file).then(res => {
                var files = res;
                let data = {
                    file: files,
                    name: this.file.name,
                    type: this.file.name.split('.')[this.file.name.split('.').length -1],
                }
                uploadFile(data).then(res => {
                    if (res.data.status == -1) {
                        return this.$message.error('上传失败，token过期');
                    } else {
                        let tmp = {
                            title: this.file.name,
                            type: 3,
                            typeid: res.data.data.id,
                            parentid: this.parentlist[this.parentlist.length - 1],
                            storeid: this.$route.params.id,
                        }
                        createFiles(tmp).then(res => {
                            if (res.data.code === 200) {
                                this.$message.success('上传成功');
                                getStoreFile(this.$route.params.id).then(res => {
                                    if (res.data.code == 200) {
                                        this.files = res.data.data;
                                        this.getCurrentFile(this.parentlist[this.parentlist.length - 1]);
                                    }
                                })
                            } else {
                                this.$message.error(res.data.message);
                            }
                        })

                    }

                })
            })

        },
        deleteFile(f) {
            this.$confirm(`该文件将会被删除, 是否继续?(若是删除文件夹，文件夹中文章与附件也会被删除)`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (f.type === 2) {
                    //说明是文件夹删除，文件夹删除需要它里面没有子文件夹才能删除，否则提示（其存在子文件夹，请先删除其子文件夹）
                    getStoreFile(this.$route.params.id).then(res => {
                        if (res.data.code == 200) {
                            this.files = res.data.data;
                            this.getCurrentFile(this.parentlist[this.parentlist.length - 1]);
                            var tmp = this.files.filter(item => item.parentid === f.id).filter(item => item.type === 2);
                            if (tmp.length > 0) {
                                this.$notify.error({
                                    title: '错误',
                                    duration: 0,
                                    dangerouslyUseHTMLString: true,
                                    message: '该文件夹内含有子文件夹。请确认子文件夹中内容无用后，<b>删除其子文件夹后再重试。</b>'
                                });
                                return;
                            } else {
                                this.delete(f.id, f.type);
                            }
                        }
                    })
                } else {
                    this.delete(f.id, f.type);
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                })
            });
        },
        delete(id, type) {
            deleteFile(id, type).then(resp => {
                if (resp.data.code == 200) {
                    this.$message.success("删除成功")
                    getStoreFile(this.$route.params.id).then(res => {
                        if (res.data.code == 200) {
                            this.files = res.data.data;
                            this.getCurrentFile(this.parentlist[this.parentlist.length - 1]);
                        }
                    })
                } else {
                    this.$message.error(resp.data.message)
                }
            })
        },
        editFile(f) {
            if (f.type === 1) {
                this.editArticle(f.typeid);
            } else {
                var input = document.querySelector('.inputReName');
                var span = document.querySelector('#filetitle');
                input.style.display = 'block';
                span.style.display = 'none';
                this.FileReName = f.filetitle;
            }
        },
        editArticle(id) {
            this.$router.push(`/write/${this.$route.params.id}/${this.parentlist[this.parentlist.length - 1]}/${id}`);
        },
        changeFileName(id) {
            updateFileName(id, this.FileReName).then(res => {
                if (res.data.code == 200) {
                    this.$notify.success('文件夹重命名成功！');
                    var input = document.querySelector('.inputReName');
                    var span = document.querySelector('#filetitle');
                    input.style.display = 'none';
                    span.style.display = 'inline-block';
                    this.FileReName = '';
                    getStoreFile(this.$route.params.id).then(res => {
                        if (res.data.code == 200) {
                            this.files = res.data.data;
                            this.getCurrentFile(this.parentlist[this.parentlist.length - 1])
                        }
                    })
                }
            })
        }
    }
}
</script>

<style scoped="scoped">
.el-icon-delete {
    color: rgb(200, 31, 31);
    font-size: 17px;
    margin: 0 10px 0 5px;
}

.inputReName {
    display: none;
    margin-left: 0;
}

.el-icon-edit {
    color: #4194f2;
    font-size: 17px;
    margin: 0 5px;
}

.el-icon-document,
.el-icon-paperclip {
    color: #4194f2;
    font-size: 25px;
}

.el-icon-folder,
.el-icon-folder-opened {
    color: #5dbcc0;
    font-size: 25px;
}

.storefile {
    min-height: 320px;
}

li {
    list-style-type: none;
    cursor: pointer;
}

li:hover {
    background: rgb(226, 240, 253);
}

.files {
    height: 60px;
    border-bottom: 1px solid #eceaea;
    margin: 0 10px;
    line-height: 60px;
    display: flex;
    justify-content: space-between;
}

.folder {
    width: 25px;
    height: 25px;
}

.fileitem {
    display: flex;
    align-items: center;
    margin: 0 10px;
    justify-content: flex-start;
}

.creator {
    font-size: 12px;
    color: #5c5c5c;
    margin-right: 10px;
}

.uploadHover {
    overflow: inherit;
    display: none;
    z-index: 99;
    position: absolute;
    background: #f5fcff;
    border-radius: 10px;
    color: #505050;
    font-size: 12px;
}

.upload:hover .uploadHover {
    display: block !important;
}

.upload button {
    margin: 0 15px;
    padding: 10px 25px;
}

.uploadHover li {
    padding: 5px 15px;
    border: 1px solid #f7f7f7;
}

#fileToUpload {
    display: none;
}

.downloadBt {
    cursor: pointer;
    font-size: 12px;
    color: #2680f6;
    margin-right: 20px;
}

.fileNav {
    font-size: 13px;
    height: 35px;
    line-height: 35px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ededed;
}

.inputFile {
    margin-left: 10px;
}

.dialog-footer {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
}
</style>